﻿using System;
using System.Net;
using System.Web;

namespace CodeContrib.Web
{
	// http://akismetapi.codeplex.com/
	public class Akismet
	{
		private readonly string _apiKey;
		private readonly string _blogUrl;
		private readonly string _userAgent;

		public string CharSet { get; set; }

		public Akismet(string apiKey, string blogUrl, string userAgent)
		{
			Guard.NotNull(apiKey, "apiKey");
			Guard.NotNull(userAgent, "userAgent");
			Guard.NotNull(userAgent, "userAgent");

			_apiKey = apiKey;
			_blogUrl = blogUrl;
			CharSet = "UTF-8";
			_userAgent = userAgent + " | Akismet/1.3";
		}

		public bool CommentCheck(AkismetComment comment)
		{
			var response = WebRequest.Create(string.Format("http://{0}.rest.akismet.com/1.1/comment-check", _apiKey)).HttpPost(CreateData(comment), CharSet, _userAgent);

			return Convert.ToBoolean(response);
		}

		private string CreateData(AkismetComment comment)
		{
			return string.Format("blog={0}&user_ip={1}&user_agent={2}&referrer={3}&permalink={4}&comment_type={5}&comment_author={6}&comment_author_email={7}&comment_author_url={8}&comment_content={9}", HttpUtility.UrlEncode(comment.BlogUrl), HttpUtility.UrlEncode(comment.UserHostAddress), HttpUtility.UrlEncode(comment.UserAgent), HttpUtility.UrlEncode(comment.Referrer), HttpUtility.UrlEncode(comment.Permalink), HttpUtility.UrlEncode(comment.CommentType), HttpUtility.UrlEncode(comment.CommentAuthor), HttpUtility.UrlEncode(comment.CommentAuthorEmailAddress), HttpUtility.UrlEncode(comment.CommentAuthorUrl), HttpUtility.UrlEncode(comment.CommentContent));
		}

		public void SubmitHam(AkismetComment comment)
		{
			WebRequest.Create(string.Format("http://{0}.rest.akismet.com/1.1/submit-ham", _apiKey)).HttpPost(CreateData(comment), CharSet, _userAgent);
		}

		public void SubmitSpam(AkismetComment comment)
		{
			WebRequest.Create(string.Format("http://{0}.rest.akismet.com/1.1/submit-spam", _apiKey)).HttpPost(CreateData(comment), CharSet, _userAgent);
		}

		public bool VerifyKey()
		{
			var response = WebRequest.Create("http://rest.akismet.com/1.1/verify-key").HttpPost(string.Format("key={0}&blog={1}", _apiKey, HttpUtility.UrlEncode(_blogUrl)), CharSet, _userAgent);

			return (response == "valid");
		}
	}
}